package com.ruoyi.web.controller.fund;

import com.google.gson.Gson;
import com.ruoyi.HouseErrorMsg;
import com.ruoyi.HouseException;
import com.ruoyi.ajax.AjaxTools;
import com.ruoyi.area.domain.HouseAreaT;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.costQuery.domain.BillVO;
import com.ruoyi.costQuery.domain.HouseCostT;
import com.ruoyi.costQuery.domain.InvoiceVO;
import com.ruoyi.costQuery.domain.MessageVO;
import com.ruoyi.costQuery.http.HttpMethodUtil;
import com.ruoyi.costQuery.service.IHouseCostQueryTService;
import com.ruoyi.data.DataUtils;
import com.ruoyi.data.NumberData;
import com.ruoyi.date.DateFormater;
import com.ruoyi.door.domain.HouseDoorT;
import com.ruoyi.door.service.IHouseDoorTService;
import com.ruoyi.project.domain.ParameterSingleVO;
import com.ruoyi.project.service.IHouseProjectTService;
import com.ruoyi.util.SysParamKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 缴费信息Controller
 * 
 * @author lijie
 * @date 2023-04-24
 */
@RestController
@RequestMapping("/fund/costQuery")
public class HouseCostQueryTController extends BaseController
{
    @Autowired
    private IHouseCostQueryTService houseCostQueryTService;

    @Autowired
    private IHouseDoorTService houseDoorTService;

    @Autowired
    private IHouseProjectTService houseProjectTService;
    private HttpServletResponse response;

    /**
     * 查询缴费信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(HouseCostT houseCostT)
    {
        startPage();
        List<HouseCostT> list = houseCostQueryTService.selectHouseCostTList(houseCostT);
        if(getDataTableSumJudge(list)){
            HouseCostT houseCostVO = houseCostQueryTService.selectHouseCostSum(houseCostT);
            houseCostVO.setAreaName("合计");
            list.add(houseCostVO);
        }
        return getDataTable(list);
    }

    /**
     * 导出缴费信息列表
     */
    @Log(title = "缴费信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HouseCostT houseCostT)
    {
        List<HouseCostT> list = houseCostQueryTService.selectHouseCostTList(houseCostT);
        if(getDataTableSumJudge(list)){
            HouseCostT houseCostVO = houseCostQueryTService.selectHouseCostSum(houseCostT);
            houseCostVO.setAreaName("合计");
            list.add(houseCostVO);
        }
        ExcelUtil<HouseCostT> util = new ExcelUtil<HouseCostT>(HouseCostT.class);
        util.exportExcel(response, list, "缴费信息数据");
    }

    /**
     * 获取缴费信息详细信息
     */
    @GetMapping(value = "/{costId}")
    public AjaxResult getInfo(@PathVariable("costId") Long costId)
    {
        return AjaxResult.success(houseCostQueryTService.selectHouseCostTByCostId(costId));
    }

    /**
     * 获取缴费信息详细信息
     */
    @GetMapping(value = "/getPrint/{costId}")
    public AjaxResult getPrint(@PathVariable("costId") Long costId)
    {
        HouseCostT houseCostVO = houseCostQueryTService.selectHouseCostTByCostId(costId);
        houseCostVO.setFormula(houseCostVO.getSpace()+"*"+houseCostVO.getBuildMoney()+"*"+houseCostVO.getPurposeMoney());
        houseCostVO.setMoneyTemp(NumberData.makeUpperCaseSum(houseCostVO.getCostMoney().toString()));
        return AjaxResult.success(houseCostVO);
    }


    /**
     * 修改缴费信息
     */
    @Log(title = "缴费信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HouseCostT houseCostT)
    {
        return toAjax(houseCostQueryTService.updateHouseCostT(houseCostT));
    }

    /**
     * 删除缴费信息
     */
    @Log(title = "缴费信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{costIds}")
    public AjaxResult remove(@PathVariable Long[] costIds)
    {
        return toAjax(houseCostQueryTService.deleteHouseCostTByCostIds(costIds));
    }

    @GetMapping(value = "/print/{costId}")
    public AjaxResult print(@PathVariable("costId") Long costId){
        BillVO billVO1 = houseCostQueryTService.getBillDetailByBillNO(costId);
        return AjaxResult.success(billVO1);
    }

    //申请发票
    @GetMapping(value = "/apply/{costId}")
    public AjaxResult apply(@PathVariable("costId") Long costId) throws HouseException {
        HouseCostT houseCostVO = houseCostQueryTService.selectHouseCostTByCostId(costId);
        HouseDoorT doorVO=new HouseDoorT();
        doorVO.setHouseId(houseCostVO.getHouseId());
        MessageVO messageVO = new MessageVO();
        doorVO = houseDoorTService.getDoorT(doorVO);
        messageVO.setCostId(costId);
        messageVO = houseCostQueryTService.selectHouseEbillT(messageVO);
        if(messageVO != null) {
            return AjaxResult.error("已开票");
        }
        if(doorVO.getTel() == null) {
            return AjaxResult.error("电话号码不能为空");
        }
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            String date = simpleDateFormat.format(new Date());
            List<InvoiceVO.ChargeDetail> list = new ArrayList<InvoiceVO.ChargeDetail>();
            InvoiceVO iv = new InvoiceVO();
            String busNo = "711001" + DateFormater.getSystemCurrentDateSimple() + houseCostVO.getSerial();
            iv.setBusNo(busNo);// 票据编号
            iv.setBillCode("0205");// 票据类型编号
            iv.setPayerType("1");// 缴费是个人还是单位
            iv.setPayer(doorVO.getUserName());// 缴费人
            iv.setPayerAgent(houseCostVO.getCreater());// 代办人
            iv.setCardType("1101");// 证件类型编码
            iv.setCreditCode(houseCostVO.getPapersCode());// 身份证号
            iv.setBusDateTime(date);// 缴费时间
            iv.setPlaceCode("001");// 开票点编码
            iv.setPayee("蒋美琪");// 收费员
            iv.setAuthor("蒋美琪");// 票据编制人
            iv.setTotalAmt(String.valueOf(houseCostVO.getCostMoney()));// 开票总金额
            iv.setRemark("");
            iv.setAlipayCode("");// 支付宝账户
            iv.setWeChatOrderNo("");// 微信支付订单号
            iv.setPayChannel("02");// 交费渠道
            iv.setTel(houseCostVO.getTel());// 交款人手机号码
            iv.setEmail("");// 交款人邮箱地址
            iv.setIdCardNo("");// 交款人身份证号码
            iv.setReviewer("蒋美琪");// 复核人
            iv.setAddress(doorVO.getAreaName() + "-" + doorVO.getGroupName() + "-" + doorVO.getUnitName() + "-"
                    + doorVO.getDoorId());
            iv.setCustom1(String.valueOf(doorVO.getSpace()));
            iv.setCustom2(houseCostVO.getTel());
            iv.setCustom3(doorVO.getSpace() + "*" + doorVO.getBuildMoney() + "*" + doorVO.getPurposeMoney()
                    + "=" + (doorVO.getSpace() * doorVO.getBuildMoney() * doorVO.getPurposeMoney()));
            InvoiceVO.ChargeDetail map1 = new InvoiceVO.ChargeDetail("ZZZX01", "住宅专项维修资金", "", "",
                    String.valueOf(doorVO.getBuildMoney() * doorVO.getPurposeMoney()),
                    String.valueOf(doorVO.getSpace()), String.valueOf(houseCostVO.getCostMoney()), "");
            list.add(map1);
            iv.setChargeDetail(list);
            HttpMethodUtil hmu = new HttpMethodUtil();
            Map map = hmu.getMessage("invoiceEBill", iv);
            if ("S0000".equals(map.get("result"))) {
                Gson gson = new Gson();
                BillVO billVO = gson.fromJson(String.valueOf(map.get("message")), BillVO.class);
                billVO.setCostId(String.valueOf(houseCostVO.getCostId()));
                houseCostQueryTService.updateDoorBill(billVO);
                ParameterSingleVO parameterSingleVO = new ParameterSingleVO();
                parameterSingleVO.setParamCode(SysParamKey.QR_CODE.getKey());
                ParameterSingleVO path1 = houseProjectTService.getSysParams(parameterSingleVO);
                File localFile = new File(path1 + billVO.getBillNo() + ".png");
                OutputStream is = new FileOutputStream(localFile);
                is.close();
                BASE64Decoder decoder = new BASE64Decoder();
                byte[] bytes = decoder.decodeBuffer(billVO.getBillQRCode());
                ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
                BufferedImage bi1 = ImageIO.read(bais);
                String path = path1 + billVO.getBillNo() + ".png";
                File file = new File(path);// 可以是jpg,png,gif格式
                ImageIO.write(bi1, "png", file);

                MessageVO mv = new MessageVO();
                mv.setCostId(houseCostVO.getCostId());
                mv.setBillSts("1");
                mv.setBillBatchCode(billVO.getBillBatchCode());
                mv.setBillNo(billVO.getBillNo());
                mv.setHouseId(houseCostVO.getHouseId());
                mv.setBusNo(busNo);
                mv.setBillQRCode(path);
                mv.setCreateTime(billVO.getCreateTime());
                mv.setPictureUrl(billVO.getPictureUrl());
                mv.setRandom(billVO.getRandom());
                houseCostQueryTService.insertBillDetail(mv);
                return AjaxResult.success("开票成功");
            }else {
                return AjaxResult.error((String) map.get("message"));
            }
        } catch (Exception e) {

        }
        return AjaxResult.success();
    }
}
